package com.example.administrator.k3xiangmu;

import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.AsyncTask;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.example.administrator.k3xiangmu.entity.ShengchangrenwudanEntity;
import com.lidroid.xutils.HttpUtils;

import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

import de.greenrobot.event.EventBus;

public class KaidanActivity extends AppCompatActivity {
    Button btname,bttjiao,btck;
    TextView tvname,tvck;
    EditText etsl,etjg;
    List<String>list=new ArrayList<>();
    String[] s=new String[0];
    String id="";
    private Toolbar toolbar;
    ProgressDialog dialog;
    HttpUtils h;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_kaidan);
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction("android.intent.action.SCANRESULT");
        registerReceiver(MsgReceiver, intentFilter);

        dialog=new ProgressDialog(this);
        setTool();
        getData();
        setView();
        setListen();
    }
    private void setTool() {
        toolbar = (Toolbar) findViewById(R.id.id_toolbar);
        toolbar.setTitle("移动开单");

        toolbar.setBackgroundColor(getResources().getColor(R.color.colorPrimary));
        setSupportActionBar(toolbar);


        toolbar.setNavigationIcon(android.R.drawable.ic_menu_revert);
        toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

    }
    private void getData(){
        dialog.show();
        UpdateTextTask2 updateTextTask = new UpdateTextTask2(this);
        updateTextTask.execute();
    }
    private void setListen(){
        btck.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                AlertDialog.Builder builder = new AlertDialog.Builder(
                        KaidanActivity.this);
                builder.setTitle("请选择仓库");
                final String[] ck={"回收","大棚","大棚卖出","大棚损耗","花店","花店卖出","花店损耗"};
                //items使用全局的finalCharSequenece数组声明
                builder.setItems(ck, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        // TODO Auto-generated method stub
                        String select_item =ck[which].toString();
                        tvck.setText(select_item+"");
                        if(select_item.equals("回收")){
                            id="536";
                        }else if(select_item.equals("大棚")){
                            id="885";
                        }else if(select_item.equals("大棚卖出")){
                            id="886";
                        }else if(select_item.equals("大棚损耗")){
                            id="887";
                        }else if(select_item.equals("花店")){
                            id="888";
                        }else if(select_item.equals("花店卖出")){
                            id="889";
                        }else if(select_item.equals("花店损耗")){
                            id="890";
                        }
                    }
                });
                builder.show();
            }
        });
        bttjiao.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if((tvname.getText().toString()+"").equals("")){
                    Toast.makeText(KaidanActivity.this,"请选择花卉",Toast.LENGTH_LONG).show();;
                    return;
                }else if((tvck.getText().toString()+"").equals("")){
                    Toast.makeText(KaidanActivity.this,"请选择仓库",Toast.LENGTH_LONG).show();;
                    return;

                }else  if((etsl.getText().toString()+"").equals("")){
                    Toast.makeText(KaidanActivity.this,"请输入数量",Toast.LENGTH_LONG).show();;
                    return;
                }else if((etjg.getText().toString()+"").equals("")){
                    Toast.makeText(KaidanActivity.this,"请输入价格",Toast.LENGTH_LONG).show();;
                    return;
                }
                UpdateTextTask3 updateTextTask = new UpdateTextTask3(KaidanActivity.this);
                updateTextTask.execute();
            }
        });
        btname.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                AlertDialog.Builder builder = new AlertDialog.Builder(
                        KaidanActivity.this);
                builder.setTitle("请选择花卉");
                //items使用全局的finalCharSequenece数组声明
                builder.setItems(s, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        // TODO Auto-generated method stub
                        String select_item = s[which].toString();
                       tvname.setText(select_item+"");
                    }
                });
                builder.show();
            }
        });
    }
    private void  setView(){
        tvck=(TextView)findViewById(R.id.tv_ck);
        btck=(Button)findViewById(R.id.btck);
        btname=(Button)findViewById(R.id.btname);
        bttjiao=(Button)findViewById(R.id.tijiao) ;
       tvname=(TextView)findViewById(R.id.tv_name);
        etjg=(EditText)findViewById(R.id.etjiage);
        etsl=(EditText)findViewById(R.id.etshuliang);
    }
    class UpdateTextTask2 extends AsyncTask<Void, Integer, Integer> {
        private Context context;

        UpdateTextTask2(Context context) {
            this.context = context;
        }

        /**
         * 运行在UI线程中，在调用doInBackground()之前执行
         */
        @Override
        protected void onPreExecute() {

            //dialog.show();
        }

        /**
         * 后台运行的方法，可以运行非UI线程，可以执行耗时的方法
         */
        @Override
        protected Integer doInBackground(Void... params) {

            try {

                Class.forName("net.sourceforge.jtds.jdbc.Driver");
                Connection dbConn = DriverManager.getConnection("jdbc:jtds:sqlserver://" + Main3Activity.ip + ";DatabaseName=" + Main3Activity.userDB + "",
                        Main3Activity.userName, Main3Activity.userPwd);
                testConnection2(dbConn);


            } catch (Exception e) {
                Log.i("asd", e.toString() + "");
                return 1;

            }


            return 5;
        }

        /**
         * 运行在ui线程中，在doInBackground()执行完毕后执行
         */
        @Override
        protected void onPostExecute(Integer integer) {
              dialog.dismiss();


        }

        /**
         * 在publishProgress()被调用以后执行，publishProgress()用于更新进度
         */
        @Override
        protected void onProgressUpdate(Integer... values) {

        }
    }

    class UpdateTextTask3 extends AsyncTask<Void, Integer, Integer> {
        private Context context;

        UpdateTextTask3(Context context) {
            this.context = context;
        }

        /**
         * 运行在UI线程中，在调用doInBackground()之前执行
         */
        @Override
        protected void onPreExecute() {

            //dialog.show();
        }

        /**
         * 后台运行的方法，可以运行非UI线程，可以执行耗时的方法
         */
        @Override
        protected Integer doInBackground(Void... params) {

            try {

                Class.forName("net.sourceforge.jtds.jdbc.Driver");
                Connection dbConn = DriverManager.getConnection("jdbc:jtds:sqlserver://" + Main3Activity.ip + ";DatabaseName=" + Main3Activity.userDB + "",
                        Main3Activity.userName, Main3Activity.userPwd);
                testConnection3(dbConn);


            } catch (Exception e) {
                Log.i("asd", e.toString() + "");
                return 1;

            }


            return 5;
        }

        /**
         * 运行在ui线程中，在doInBackground()执行完毕后执行
         */
        @Override
        protected void onPostExecute(Integer integer) {
            //  dialog.dismiss();
            Toast.makeText(KaidanActivity.this,"提交成功",Toast.LENGTH_LONG).show();
            finish();


        }

        /**
         * 在publishProgress()被调用以后执行，publishProgress()用于更新进度
         */
        @Override
        protected void onProgressUpdate(Integer... values) {

        }
    }
    public void testConnection2(Connection con) throws java.sql.SQLException {

        try {

            String sql = "select* from t_ICItem";

            Statement stmt = con.createStatement();// 创建Statement
            ResultSet rs = stmt.executeQuery(sql);// ResultSet类似Cursor


            while (rs.next()) {// <code>ResultSet</code>最初指向第一行
                list.add(rs.getString("FName"));



            }
            s=new String[list.size()];
            for(int i=0;i<list.size();i++){
                s[i]=list.get(i);
            }



            rs.close();
            stmt.close();
        } catch (SQLException e) {

            System.out.println(e.getMessage().toString() + "dddddddddddd")
            ;


        } finally {
            //Toast.makeText(MainActivity.this,ss, Toast.LENGTH_LONG).show();
            if (con != null)
                try {
                    con.close();
                } catch (SQLException e) {
                }
        }
    }
    public void testConnection3(Connection con) throws java.sql.SQLException {
        CallableStatement  callStmt = null;
        try {
            callStmt=con.prepareCall("{call [x_chuku] (?,?,?,?)}");
            callStmt.setString(1,tvname.getText().toString());
            callStmt.setString(2,etsl.getText().toString());
            callStmt.setString(3,etjg.getText().toString());
            callStmt.setString(4,id);
            callStmt.execute();



        } catch (SQLException e) {

            System.out.println(e.getMessage().toString() + "dddddddddddd")
            ;


        } finally {
            if (null != callStmt) {
                callStmt.close();
            }
            //Toast.makeText(MainActivity.this,ss, Toast.LENGTH_LONG).show();
            if (con != null)
                try {
                    con.close();
                } catch (SQLException e) {
                }
        }
    }
    private BroadcastReceiver MsgReceiver = new BroadcastReceiver() {

        @Override
        public void onReceive(Context context, Intent intent) {
            // TODO Auto-generated method stub
            String action = intent.getAction();
            System.out.print(action);
            //android.intent.action.SCANRESULT
            if (action.equals("android.intent.action.SCANRESULT")){
                String mMsg = intent.getStringExtra("value");

            }

        }
    };


    protected void onDestroy() {
        unregisterReceiver(MsgReceiver);
        super.onDestroy();
    };
}
